<template>
  <div class="user-list-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input placeholder="请输入昵称" v-model="search.nickname" clearable style="width: 200px;" />
      <el-select v-model="search.role" placeholder="请选择角色" clearable style="width: 200px; margin-left: 20px;">
        <el-option
          v-for="item in roleOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="search.active" placeholder="请选择状态" clearable style="width: 200px; margin-left: 20px;">
        <el-option label="启用" value="true"></el-option>
        <el-option label="禁用" value="false"></el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="fetchUserList" style="margin-left: 20px;">搜索</el-button>
    </div>

    <!-- 用户列表表格 -->
    <el-table :data="filteredUserList" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="nickname" label="昵称"></el-table-column>
      <el-table-column prop="phone" label="电话号码"></el-table-column>
      <el-table-column prop="roleLabel" label="角色"></el-table-column>
      <el-table-column prop="active" label="状态">
        <template slot-scope="{row}">
          <el-tag :type="row.active ? 'success' : 'danger'">
            {{ row.active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="{row}">
          <el-button size="mini" @click="handleEditRole(row)">修改角色</el-button>
          <el-button size="mini" @click="toggleActiveStatus(row)">
            {{ row.active ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page.sync="currentPage"
      @current-change="fetchUserList"
      style=" margin-top: 20px;"
    />

    <!-- 角色修改弹窗 -->
    <el-dialog title="修改用户角色" :visible.sync="dialogVisible" width="30%" custom-class="custom-dialog" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" class="form-content">
        <el-form-item label="用户昵称">
          <span>{{ editForm.nickname }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRoleChange">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      userList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      search: {
        nickname: '',
        role: '',
        active: ''
      },
      dialogVisible: false,
      editForm: {
        id: '',
        nickname: '',
        phone: '',
        role: '',
        active: true
      },
      roleOptions: [
        { label: '普通用户', value: 'CUSTOMER' },
        { label: '普通管理员', value: 'ADMIN' },
        { label: '超级管理员', value: 'SUPER_ADMIN' }
      ],
      refreshTimer: null // 定时器引用
    };
  },
  computed: {
    filteredUserList() {
      return this.userList.filter(user => 
        (user.nickname.includes(this.search.nickname) || !this.search.nickname) &&
        (!this.search.role || user.role == this.search.role) &&
        (this.search.active == '' || user.active.toString() == this.search.active)
      );
    }
  },
  mounted() {
    this.fetchUserList();
    this.startAutoRefresh(); // 启动定时器
  },
  beforeDestroy() {
    this.stopAutoRefresh(); // 清除定时器
  },
  methods: {
    fetchUserList(page = this.currentPage) {
      axios.get('/api/admin/user/getUserList').then(res => {
        if (res.data.code == 1) {
          this.total = res.data.data.total;
          this.userList = res.data.data.userList.map(user => ({
            ...user,
            roleLabel: this.getRoleLabel(user.role)
          })).slice((page - 1) * this.pageSize, page * this.pageSize);
        } else {
          console.error('获取用户列表失败', res.data.msg);
        }
      });
    },
    getRoleLabel(roleKey) {
      const roleMap = {
        CUSTOMER: '普通用户',
        ADMIN: '普通管理员',
        SUPER_ADMIN: '超级管理员'
      };
      return roleMap[roleKey] || roleKey;
    },
    handleEditRole(user) {
      this.editForm = { ...user };
      this.dialogVisible = true;
    },
    submitRoleChange() {
      const { id, role } = this.editForm;

      // 如果是修改为超级管理员，二次确认
      if (role == 'SUPER_ADMIN') {
        this.$confirm('确定要将该用户设置为超级管理员吗？这会强制你退出当前账号。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.updateUserRole(id, role);
        }).catch(() => {});
      } else {
        this.updateUserRole(id, role);
      }
    },
    updateUserRole(id, role) {
      axios.post('/api/admin/updatePersonalInformationById', {
        id,
        role,
        active: this.editForm.active
      }).then(res => {
        if (res.data.code == 1) {
          this.$message.success('角色修改成功');
          this.fetchUserList();

          // 如果修改为超级管理员，登出自己
          if (role == 'SUPER_ADMIN') {
            this.logout();
          }

          this.dialogVisible = false;
        } else {
          this.$message.error('角色修改失败');
        }
      });
    },
    toggleActiveStatus(user) {
      const newActiveStatus = !user.active;
      axios.post('/api/admin/updatePersonalInformationById', {
        id: user.id,
        role: user.role,
        active: newActiveStatus
      }).then(res => {
        if (res.data.code == 1) {
          this.$message.success(newActiveStatus ? '账号已启用' : '账号已禁用');
          this.fetchUserList();
        } else {
          this.$message.error('操作失败');
        }
      });
    },
    logout() {
      axios.get('/api/login/logout').catch(() => {});
      this.$router.push({ path: '/login' });
    },
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        if (this.user.active&&this.$route.name=="Account") {
          this.fetchUserList(this.currentPage);
        }
      }, 4000);
    },
    stopAutoRefresh() {
      clearInterval(this.refreshTimer);
      this.refreshTimer = null;
    }
  }
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.custom-dialog .el-dialog__header {
  background-color: #409EFF;
  color: white;
  padding: 15px;
  font-size: 16px;
}

.custom-dialog .el-dialog__title {
  color: white;
}

.form-content {
  padding: 0 20px;
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
}
</style>